package ssi.staaar;

import java.util.Date;

import ssi.staaar.ciphers.SymCipher;
import ssi.staaar.control.StaaarControl;
import ssi.staaar.exceptions.ServerException;
import ssi.staaar.managers.KeyManager;
import ssi.staaar.util.Javabean2JSON;
import ssi.staar.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class Staaar extends Activity {
	public static final int REG = 1;
	public static final String PREFS_NAME = "StaaarPref";
	private static final int REC = 2;
	public static final float DEFAULT_METERS = 10;
	public static final long DEFAULT_MINUTES = 5*1000;
	public static final float DEFAULT_RADIUS_METERS = 500;
	private AlertDialog.Builder builder, builderServer, builderWrongPwd, builderPenalty;
	private int remainingTries = 5;
	private static long PENALTY_TIME = 10*60*1000; //10 minuti
	private static SharedPreferences settings;
	public static StaaarControl stControl;
	
	
	public String getServerKey() {
		return getString(R.string.serverKey);
	}

	private boolean checkConnectivityFor(int type) {
		ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conMgr.getNetworkInfo(type).getState() == NetworkInfo.State.CONNECTED
		    || conMgr.getNetworkInfo(type).getState() == NetworkInfo.State.CONNECTING) {
		    return true;
		}
		return false;
	}

	public void goToRecoveryActivity(View view) {
		Intent iRec = new Intent();
		iRec.setClass(getApplicationContext(), RecoveryActivity.class);
		startActivityForResult(iRec, REC);
	}

	public void goToRegistrationActivity(View view) {
		Intent iReg = new Intent();
		iReg.setClass(getApplicationContext(), RegistrationActivity.class);
		startActivityForResult(iReg, REG);
	}

	public void login(View view) {
		String username = settings.getString("Username", "");
		EditText pwd = (EditText)findViewById(R.id.pwdEditText);
		stControl = new StaaarControl(getApplicationContext(),
				getString(R.string.serverAddress), 
				Integer.parseInt(getString(R.string.serverPort)),
				getString(R.string.keyPassword)
				);
		try {
			stControl.startConnection();
			boolean logged = stControl.login(username, pwd.getText().toString());
			if (logged) {
				Log.d("LoginControl", "Logged");
				Editor settingsEditor = settings.edit();
				settingsEditor.putInt("SessionId", stControl.getSessionId());
				settingsEditor.putString("SessionKey", SymCipher.keyToString(stControl.getSessionKey()));
				settingsEditor.putString("User", Javabean2JSON.toJSONObject(stControl.getUser()).toString());
				settingsEditor.commit();
				Intent i = new Intent();
				i.setClass(getApplicationContext(), MessageListActivity.class);
				startActivity(i);
				finish();
			} else {
				String wrongStr=getString(R.string.wrong_password);
				wrongStr = wrongStr.replace("{number}", "" + (remainingTries-1));
				builderWrongPwd.setMessage(wrongStr);
				AlertDialog wrPwd = builderWrongPwd.create();
				wrPwd.show();
				remainingTries--;	
				if (remainingTries==0){
					Editor settingsEditor = settings.edit();
					settingsEditor.putLong("WrongPasswdPenaltyTime", new Date().getTime());
					settingsEditor.commit();
					System.exit(-1);
				}
			}
		} catch (ServerException e) {
			AlertDialog alertServer = builderServer.create();
			alertServer.show();
			e.printStackTrace();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode,
	        Intent data) {
		Log.d("REC", "return" + resultCode);
		if (resultCode == RESULT_OK) {
			setContentView(R.layout.mainregistered);
			setUpRegistered();
		}
	}

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    settings = getSharedPreferences(PREFS_NAME, 0);
		builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.app_name)
			.setMessage(R.string.no_internet)
			.setNeutralButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					finish();
				}
	    });
		builderServer = new AlertDialog.Builder(this);
	    builderServer.setTitle(R.string.app_name)
	    	.setMessage(R.string.server_unreachable)
		    .setNeutralButton("OK", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		             dialog.dismiss();
		        }
		});
	    builderWrongPwd = new AlertDialog.Builder(this);
	    builderWrongPwd.setTitle(R.string.app_name)
    	.setMessage(R.string.wrong_password)
	    .setNeutralButton("OK", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int id) {
	             dialog.dismiss();
	        }
	    });
	    builderPenalty = new AlertDialog.Builder(this);
	    builderPenalty.setTitle(R.string.app_name)
    	.setMessage(R.string.penalty_reached)
	    .setNeutralButton("Exit", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int id) {
	             dialog.dismiss();
	             System.exit(-1);
	        }
	    });
		if (!checkConnectivityFor(ConnectivityManager.TYPE_MOBILE) && 
		    !checkConnectivityFor(ConnectivityManager.TYPE_WIFI)) 
		{
		    	AlertDialog alert = builder.create();
				alert.show();
		} 
		boolean firstStart = settings.getBoolean("firstStart", true);
		if (firstStart) {
			KeyManager.storeServerKey(getString(R.string.serverKey),  getApplicationContext());
			Editor e = settings.edit();
			e.putBoolean("firstStart", false);
			e.commit();	
		}
	    boolean registered = settings.getBoolean("Registered", false);
	    if (!registered)
	    	setContentView(R.layout.main);
	    else {
	    	long remainingPenaltyTime = settings.getLong("WrongPasswdPenaltyTime", 0);
	    	if (remainingPenaltyTime != 0) {
	    		System.out.println("PENALTY TIME: " + remainingPenaltyTime);
	    		long now = new Date().getTime();
	    		if ((now - remainingPenaltyTime) < PENALTY_TIME) {
	    			AlertDialog penaltyDialog = builderPenalty.create();
	    			penaltyDialog.show();
	    		}
	    	}
	    	setContentView(R.layout.mainregistered);
	    	setUpRegistered();
	    }
	}

	@Override 
	protected void onResume(){
		super.onResume();
	}

	private void setUpRegistered() {
		String username = settings.getString("Username", "");
    	final TextView text = (TextView)findViewById(R.id.welcomeRegistered);
    	String t = getString(R.string.welcome_registered);
    	t = t.replace("{Username}", username);
		text.setText(t);
	}
}
